package com.ibeetl.admin.core.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    
    public static Date MAX_DATE = maxDate();
   
    
    
    public static String now() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
    
    public static String now(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }
    
    private static Date maxDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse("9999-12-31 23:59:59");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    public static String format(Date date, String pattern) {
        if (pattern == null) {
            pattern = "yyyy-MM-dd";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }
    public static Date getDate(String strDate) {
		if (StringUtils.isBlank(strDate)) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
        format.setLenient(false);
        try {
            return format.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println("com.sunzhe.util.DateUtils getDate() ： 时间格式不正确，应为yyyy-MM-dd");
			return null;
		}
	}

    public static Date getDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
        format.setLenient(false);
        try {
            return format.parse(strDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            return null;
        }
    }

    public static Date getDate(String strDate, String pattern, Integer days) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
        format.setLenient(false);
        try {

            Date date = format.parse(strDate);

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.DATE, days);//增加一天
            return cal.getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            return null;
        }
    }
}
